import { login, getInfo, getInfoById } from '@/api/user'
import { getToken, setToken, removeToken, setTokenTimeStamp } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken() || '',
    userInfo: {}
  }
}

const state = getDefaultState()

const mutations = {
  // 1.浅克隆state
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  // 2.修改state中的token
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  // 3.修改state中name
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  }
}

const actions = {
  // 发送登录请求
  login({ commit }, userInfo) {
    // const { mobile, password } = userInfo
    return new Promise((resolve, reject) => {
      (async function() {
        try {
          const res = await login(userInfo)
          console.log(res)
          // 设置token
          commit('SET_TOKEN', res.data)
          setToken(res.data)
          // 储存时间戳
          setTokenTimeStamp(Date.now())
          // 跳转首页
          // router.push(path || '/')
          resolve()
        } catch (error) {
          // console.log(error)
          // 失败
          reject(error)
        }
      })()
    })
  },

  // 获取用户信息
  getInfo({ commit, dispatch }) {
    return new Promise((resolve, reject) => {
      // 发送ajax获取用户信息
      (async function() {
        try {
          const res = await getInfo()
          console.log('获取资料成功', res)
          // 调用获取用户图像的方法
          const data = await dispatch('getInfoById', res.data.userId)

          // 设置用户信息
          commit('SET_USERINFO', { ...data, ...res.data })
          resolve(res.data.roles.menus)
        } catch (error) {
          reject(error)
        }
      })()
    })
  },
  // 获取用户图像
  getInfoById(context, id) {
    return new Promise((resolve, reject) => {
      // 发送ajax获取用户信息
      (async function() {
        try {
          const res = await getInfoById(id)
          console.log('获取用户基本信息', res)
          resolve(res.data)
        } catch (error) {
          reject(error)
        }
      })()
    })
  },

  // 退出登录
  logout({ commit, state }) {
    // 清空本地储存的token
    removeToken()
    // 重置state
    commit('RESET_STATE')
    // 重置router
    resetRouter()
  },
  //  清除token 重置state
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

